const fs = require('fs')
const path = require('path')
const os = require('os')
const { execSync } = require('child_process')

const utils = require('../../utils')

const platform  = os.platform()
const task = []

exports.task = task

//  设置复制文件任务
exports.setIntervalCopyFile = (sourcePath, targetPath, duration) => {
  const copy = copyFile(sourcePath, targetPath)
  if (copy) {
    const timer = setInterval(() => {
      copyFile(sourcePath, targetPath)
    }, duration)
    task.push({sourcePath, targetPath, timer})
  }

  return copy
}

//  清除计时复制文件任务
exports.clearIntervalCopyFile = (sourcePath, targetPath) => {
  const taskIndex = task.findIndex(task => task.sourcePath === sourcePath && task.targetPath === targetPath)

  if (taskIndex >= 0) {
    clearInterval(task[taskIndex].timer)
    task.splice(taskIndex , 1)

    return true
  }

  return false
}

function copyFile(source, target) {
  const timestamp = utils.parseTime(Date.now(), '{y}-{m}-{d} {h}-{i}-{s}')
  const fileName = path.basename(source)
  const targetPath = target + '\\' + fileName + ' - ' + timestamp

  try {
    if (platform  === 'win32') {
      const cmd = `xcopy "${source}" "${targetPath}" /E /I /Y`
      execSync(cmd)
    } else if (platform  === 'linux') {
      const cmd = `cp ${source} ${target}`
      execSync(cmd)
    }

    return true
  } catch (e) {
    console.log(e)
    return false
  }
}
